<template>
  <span>
    {{countDown}}
  </span>
</template>
<script>
export default {
  data() {
    return {
      countDown: '',
      timer: ''
    }
  },
  props: {
    deadLine: {
      type: String
    },
    callback: {
      type: Function,
      default: ''
    }
  },
  created() {
    this.timerStart()
  },
  beforeDestroy() {
    clearInterval(this.timer)//关闭当前timer
  },
  watch: {
    deadLine: function (curVal, oldVal) {
      clearInterval(this.timer)//关闭当前timer
      this.timerStart()
    }
  },
  methods: {
    fixNumber(num, length) {
      return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num
    },
    fixHMS(time) {
      var hour = Math.floor(time / 3600)
      var min = Math.floor((time - hour * 3600) / 60)
      var secound = Math.floor(time - hour * 3600 - min * 60)
      return this.fixNumber(hour, 2) + ':' + this.fixNumber(min, 2) + ':' + this.fixNumber(secound, 2)
    },
    timerStart() {
      if (!this.deadLine || this.deadLine <= 0) {
        this.countDown = this.fixHMS(0)
        return
      }
      var self = this
      var interval = 1000
      var currenTime = this.deadLine
      self.countDown = self.fixHMS(currenTime)
      self.timer = setInterval(function () {
        currenTime = currenTime - 1
        self.countDown = self.fixHMS(currenTime)
        if (currenTime <= 0) {
          clearInterval(self.timer)
          if (self.callback && self.callback instanceof Function) {
            self.callback()
          }
        }
      }, interval)
    }
  }
}
</script>
